/**
 * 
 */
package com.miolr.core.struts2;

import java.io.File;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.interceptor.FileUploadInterceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * @author iday
 *  接收来自swfupload上传的文件，主要是swfupload无法上传multipart/form-data格式的数据
 */
public class SwfUploadInterceptor extends FileUploadInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8450767783682906097L;

	protected static final Logger LOG = LoggerFactory
			.getLogger(SwfUploadInterceptor.class);

	private String multipartSaveDir;

	/**
	 * @param multipartSaveDir
	 *            the multipartSaveDir to set
	 */
	@Inject(StrutsConstants.STRUTS_MULTIPART_SAVEDIR)
	public void setMultipartSaveDir(String multipartSaveDir) {
		this.multipartSaveDir = multipartSaveDir;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts2.interceptor.FileUploadInterceptor#intercept(com.
	 * opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ac = invocation.getInvocationContext();

		HttpServletRequest request = (HttpServletRequest) ac
				.get(ServletActionContext.HTTP_REQUEST);

		String contentType = request.getContentType();
		if (contentType != null
				&& contentType.contains("application/octet-stream")) {
			String[] dispos = request.getHeader("Content-Disposition").split(
					"; ");
			String fileName = Calendar.getInstance().getTimeInMillis()
					+ dispos[2].substring(10, dispos[2].length() - 1);
			String inputName = dispos[1].substring(6, dispos[1].length() - 1);
			String contentTypeName = inputName + "ContentType";
			String fileNameName = inputName + "FileName";
			String fileContentType = URLConnection
					.guessContentTypeFromName(fileName);

			File file = new File(
					getSaveDir((ServletContext) ac
							.get(ServletActionContext.SERVLET_CONTEXT))
							+ File.separator + fileName);
			FileUtils.copyInputStreamToFile(request.getInputStream(), file);

			ValidationAware validation = null;

			Object action = invocation.getAction();

			if (action instanceof ValidationAware) {
				validation = (ValidationAware) action;
			}

			if (acceptFile(action, file, fileName, fileContentType, inputName,
					validation, ac.getLocale())) {
				Map<String, Object> params = ac.getParameters();
				params.put(inputName, file);
				params.put(contentTypeName, fileContentType);
				params.put(fileNameName, fileName);
			}
		}
		return invocation.invoke();
	}

	/**
	 * Return the path to save uploaded files to (this is configurable).
	 * 
	 * @return the path to save uploaded files to
	 * @param servletContext
	 *            Our ServletContext
	 */
	private String getSaveDir(ServletContext servletContext) {
		String saveDir = multipartSaveDir.trim();

		if (saveDir.equals("")) {
			File tempdir = (File) servletContext
					.getAttribute("javax.servlet.context.tempdir");
			if (LOG.isInfoEnabled()) {
				LOG.info("Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir");
			}

			if (tempdir != null) {
				saveDir = tempdir.toString();
				setMultipartSaveDir(saveDir);
			}
		} else {
			File multipartSaveDir = new File(saveDir);

			if (!multipartSaveDir.exists()) {
				if (!multipartSaveDir.mkdirs()) {
				}
			}
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("saveDir=" + saveDir);
		}

		return saveDir;
	}

}
